import React, { useState, useEffect, useCallback, useRef } from "react";
import "./Toast.scss";

type ToastType = "success" | "error" | "info";

interface ToastProps {
	type?: ToastType;
	title?: string;
	content?: string;
	position?: ToastPosition;
	duration?: number;
}

type ToastPosition = "top" | "bottom" | "center";

//@ts-ignore
const Toast = React.forwardRef((props, ref) => {
	const [visible, setVisible] = useState(false);
	const [toastData, setToastData] = useState<{
		type: ToastType;
		title: string;
		content: string;
		position: ToastPosition;
	}>({
		type: "info",
		title: "",
		content: "",
		position: "bottom",
	});
	const [animationDuration, setAnimationDuration] = useState(3600);
	const icons = {
		success: "✔️",
		error: "❌",
		info: "ℹ️",
	};
	// 使用 useRef 存储定时器 ID
	const timeoutRef = useRef<NodeJS.Timeout | null>(null);

	// 缓存 getIcon 函数
	const getIcon = useCallback((type: ToastType) => icons[type], [icons]);

	// 通过 ref 暴露 show 和 hide 方法
	React.useImperativeHandle(ref, () => ({
		show({
			type = "info",
			title = "",
			content = "",
			position = "bottom",
			duration = 3600,
		}: ToastProps) {
            if(visible){
                setVisible(false);
                if (timeoutRef.current) clearTimeout(timeoutRef.current);
                setTimeout(() => {
					showToast(type, title, content, position, duration);
				}, 300);
            }else{
                showToast(type, title, content, position, duration);
            }
		},
		hide() {
			if (timeoutRef.current) {
				clearTimeout(timeoutRef.current);
				timeoutRef.current = null;
			}
			setVisible(false);
		},
	}));


    // 提取出 showToast 方法，便于在 show 内部多次调用
	const showToast = (
		type: ToastType,
		title: string,
		content: string,
		position: ToastPosition,
		duration: number
	) => {
		setToastData({ type, title, content, position });
		const fadeInDuration = 300;
		const fadeOutDuration = 300;
		const fadeOutDelay = Math.max(duration - fadeInDuration - fadeOutDuration, 0);
		setAnimationDuration(fadeOutDelay);
		setVisible(true);

		// 清理上现有定时器
		if (timeoutRef.current) clearTimeout(timeoutRef.current);
		// 设置定时器隐藏 Toast
		timeoutRef.current = setTimeout(() => {
			setVisible(false);
		}, duration);
	};


	// 清理定时器
	useEffect(() => {
		return () => {
			if (timeoutRef.current) clearTimeout(timeoutRef.current);
		};
	}, []);

	return visible ? (
		<div
			className={`toast-container ${toastData.type} ${toastData.position}`}
			style={
				{
					"--fade-out-delay": `${Math.max(
						animationDuration - 600,
						0
					)}ms`,
				} as React.CSSProperties
			}
		>
			<div className="toast-icon">{getIcon(toastData.type)}</div>
			<div className="toast-content">
				{toastData.title && (
					<div className="toast-title">{toastData.title}</div>
				)}
				<div className="toast-text">{toastData.content}</div>
			</div>
		</div>
	) : null;
});

export default Toast;
